package gui.menu;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.MouseEvent;
import java.awt.event.MouseWheelEvent;
import java.util.ArrayList;

import tiles.IsometricSprite;
import gui.menu.addons.ToolMenuItemPickerItem;
import gui.menu.addons.ToolMenuItem;
import gui.menu.items.Barnhouse;

/**
 * Different tools
 * @author kolmas
 *
 */
public class ToolMenuItemPicker implements ToolMenuItem {


	private final Color BG_COLOR = new Color(51, 51, 51,200);
	
	/**
	 * Width - Width of the menu
	 * In_row - How many in row
	 */
	private int width, in_row;

	/**
	 * Sprite
	 */
	private IsometricSprite tile;
	/**
	 * Main rectangle
	 */
	private Rectangle rect;
	/**
	 * Last items point
	 */
	private Point lastItem;
	/**
	 * All items
	 */
	
	private ToolMenuItemPickerItem activeItem = null;
	private ArrayList<ToolMenuItemPickerItem> items = null;

	private final int OPTIONS_WIDTH = 80;
	private final int OPTIONS_HEIGHT = 80;
	
	public ToolMenuItemPicker() {
		addItem(new Barnhouse());
	}

	@Override
	public void draw(Graphics g, int x, int y) {
		if (items == null) 
			return;
		rect = new Rectangle(x, y, width, OPTIONS_HEIGHT*(lastItem.y + 1));
		g.setColor(BG_COLOR);
		g.fillRect(rect.x, rect.y, rect.width, rect.height);
		synchronized (items) {
			for (ToolMenuItemPickerItem tmi : items) {
				tmi.setIsometricPoint(tile);
				tmi.draw(g, x, y);
			}
		}
	}

	@Override
	public int getHeight() {
		return rect.height;
	}

	@Override
	public boolean inBounds(Point p) {
		if (rect == null) 
			return false;
		return rect.contains(p);
	}

	@Override
	public void mouseAction(MouseEvent evt) {
		synchronized (items) {
			for (ToolMenuItemPickerItem tmi : items) {
				if (tmi.contains(evt.getPoint())) {
					tmi.mouseAction(evt);
					activeItem = tmi;
				} else {
					tmi.setHighlight(false);
				}
			}
		}

	}

	@Override
	public void setTile(IsometricSprite iso) {
		this.tile = iso;
	}

	@Override
	public void setWidth(int width) {
		this.width = width;
		in_row = width / OPTIONS_WIDTH;
	}

	private void addItem(ToolMenuItemPickerItem mi) {
		if (items == null) {
			items = new ArrayList<ToolMenuItemPickerItem>();
		}
		Point tmp = new Point((lastItem == null ? 0 : (lastItem.x > in_row ? 0
				: lastItem.x + 1)), (lastItem == null ? 0
				: (lastItem.x > in_row ? lastItem.y + 1: lastItem.y)));
		lastItem = tmp;

		mi.setPoint(tmp);
		items.add(mi);
	}

	@Override
	public void mainMenuClosed() {
		activeItem = null;
		synchronized (items) {
			for (ToolMenuItemPickerItem tmi : items) {
				tmi.mainMenuClosed();
			}
		}
	}

	@Override
	public void mouseWheelAction(MouseWheelEvent evt) {	
		if (activeItem != null) {
			activeItem.mouseScrolled(evt);
		}
	}
}
